package com.atfzr.lock;


import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 望夜
 * @date 2023/8/16---14:17
 * @SuppressWarnings({"all"}) 公平锁与非公平锁
 *  默认非公平锁， 因为公平锁频繁切换线程浪费cpu资源
 */
public class SaleTicketDemo {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(()-> {for(int i =0; i < 55; i++) ticket.sale();},"a").start();
        new Thread(()-> {for(int i =0; i < 55; i++) ticket.sale();},"b").start();
        new Thread(()-> {for(int i =0; i < 55; i++) ticket.sale();},"c").start();
    }

}
class Ticket{ //资源类，模拟3个售票员卖完50张票
    private int number = 50;
    ReentrantLock lock = new ReentrantLock(); //默认false -> 非公平锁

    public void sale(){
        lock.lock();
        try {
            if(number>0){
                System.out.println(Thread.currentThread().getName() + "卖出第：\t" + (number--) + "\t 还剩下:" + number);
            }
        } finally {
            lock.unlock();
        }

    }

}

